<template>
  <div class="main-app">
    <!-- <my-header :addToDo="addTodo"/> -->
    <my-header :addTodo="addTodo" />
    <my-list :todos="todos" :deleteTodo="deleteTodo" :updateTodo="updateTodo" />
    <my-footer :todos="todos" :checkAll="checkAll" :clearAllCompleteTodos="clearAllCompleteTodos" />
  </div>
</template>
<script lang='ts'>
import { defineComponent, onMounted, reactive, toRefs, watch } from 'vue'
import MyHeader from './components/Header.vue'
import MyList from './components/List.vue'
import MyFooter from './components/Footer.vue'
import { saveTodos, readTodos } from './utils/localStorageUtils'
// 引入接口
import { ToDo } from './types/todos'
export default defineComponent({
  name: 'App',
  components: {
    MyHeader, MyList, MyFooter
  },
  // 数据应该用数组来存储，数组中的每一个数据都是一个对象，对象中应该有三个属性(id,title,isCompleted)
  // 把数据暂时定义在App.vue父组件中
  setup() {
    // const state = reactive<{ todos: ToDo[] }>({
    //   todos: [
    //     { id: 1, title: '宝马', isCompleted: true },
    //     { id: 2, title: '奔驰', isCompleted: true },
    //     { id: 3, title: '奥迪', isCompleted: false },
    //     { id: 4, title: '法拉第', isCompleted: true },
    //     { id: 5, title: '法拉第', isCompleted: false },
    //   ]
    // })
    const state = reactive<{ todos: ToDo[] }>({
      todos: []
    })
    //界面加载完毕之后过了一会再读取数据
    onMounted(() => {
      setTimeout(() => {
        state.todos = readTodos()
      }, 2000)
    })
    // 添加数据的方法
    const addTodo = (todo: ToDo) => {
      state.todos.unshift(todo)
    }
    // 删除数据的方法
    const deleteTodo = (index: number) => {
      state.todos.splice(index, 1)
    }
    // 修改todo的isCompleted属性的状态
    const updateTodo = (todo: ToDo, isCompleted: boolean) => {
      console.log("当前的todo是", todo);
      console.log("当前的isCompleted是", isCompleted);
      todo.isCompleted = isCompleted
    }
    //全选或者全不选的方法
    const checkAll = (isCompleted: boolean) => {
      // 遍历数组
      state.todos.forEach(todo => {
        todo.isCompleted = isCompleted
      })
    }
    // 清理所有已经选中的数据
    const clearAllCompleteTodos = () => {
      // 将todo.isCompleted为false的保存下来,其它的全部都过滤掉
      state.todos = state.todos.filter(todo => !todo.isCompleted)
    }
    // 监视操作:如果todos数组的数据发生了变化,直接存储到浏览器的缓存中
    // watch(()=>state.todos,(value)=>{
    //   //保存浏览器的缓存中
    //   localStorage.setItem('todos_key',JSON.stringify(value))
    // })

    // watch(() => state.todos, (value) => {
    //   //保存浏览器的缓存中
    //   saveTodos(value)
    // }, { deep: true })
    // 可以简写成下面的方式
    watch(() => state.todos, saveTodos, { deep: true })

    return {
      ...toRefs(state),
      addTodo,
      deleteTodo,
      updateTodo,
      checkAll,
      clearAllCompleteTodos
    }
  }
})
</script>
<style scoped lang="scss">
.main-app {
  width: 600px;
  padding: 10xp;
  margin: 20px auto;
  background-color: pink;
  border: 2px solid blue;
}
</style>